<template>
  <div>
    <!--element-loading-background="rgba(255, 255, 255, 0.5)"-->
    <div :style="{height: this.height}" :class="{'cancelMinHeight': this.cancelMinHeight}">
      <el-table size="mini" stripe class="pal-table"  border style="width: 100%;" height="100%" highlight-current-row
                v-loading="loading"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                :data="tableData"
                @sort-change = "sortChange"
                @selection-change="selectionChange"
                @current-change="currentChange"
                @row-click = "rowClick">
        <el-table-column type="selection" fixed="left" align="center" width="55" v-if="showSelection"></el-table-column>
        <el-table-column fixed label="序号" width="55" align="center" v-if="showIndex">
          <template scope="scope"><span>{{scope.$index+(params.page - 1) * params.limit + 1}} </span></template>
        </el-table-column>
        <slot></slot>
      </el-table>
    </div>
    <div class="pal-pagination" v-if="paging">
      <div class="fl">
        <slot name="pagination-btns"></slot>
      </div>
      <el-pagination background
        v-if="paging"
        @size-change="limitChange"
        @current-change="pageChange"
        :current-page.sync="params.page"
        :page-size="params.limit"
        :page-sizes="[20, 50, 100, 500, 1000]"
                     align="right"
        layout="total, prev, pager, next, sizes, jumper"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>
<style lang="less">
 .pal-table{
   .el-loading-spinner i{
     font-size: 40px;
     margin-bottom: 10px;
   }
 }
 .cancelMinHeight{
   .pal-table{
     .el-table__body-wrapper{
       height: auto!important;
     }
   }
 }
</style>
<style lang="less" scoped>
  .pal-pagination{
    text-align: center;
    padding: 15px;
    padding-bottom: 0;
    .el-pagination{
      margin-top: 0;
    }
  }
</style>
<script>
export default {
  props: {
    // 参数  默认返回分页和条数
    params: {
      type: [Object, String, Number],
      default: function () {
        return { page: 1, limit: 20 }
      }
    },

    data: {
      type: [Array],
      default: function () {
        return []
      }
    },

    cancelMinHeight: {
      default: false
    },

    // 分页
    paging: {
      default: true
    },
    // 多选框
    showSelection: {
      default: false
    },
    // 序号
    showIndex: {
      default: false
    },

    tableHeight: {
      default: '600px'
    }
  },
  data () {
    /*
     *表格查询格式
     *{
 "filters": [   表头过滤
   {
     "operator": "string",   模糊or精确
     "property": "string",  字段
     "value": {}   //值
   }
 ],
 "page": 0,   //当前页
 "query": [   //表格查询
   {
     "property": "string",  字段
     "value": {}   值
   }
 ],
 "sidx": "string",   排序字段名
 "size": 0,          每页展示条数
 "sort": "string"    排序方式（升序或降序）
}
     * */
    return {
      api: '', // 请求接口
      requestMethod: 'post', // 默认post请求
      query: [], // 表格查询条件
      tableData: [],
      total: 0, // 总条数
      tableDate: [], // 表格数据
      loading: false, // loading动画
      requestParams: {},
      callback: null,
      successback: null,
      errorback: null,
      selections: [],
      height: ''
    }
  },
  watch: {
    data: function () {
      if (this.data) {
        this.tableData = this.data
      }
    },
    tableHeight: function () {
      this.watchTableHeight()
    }
  },
  created () {
    this.watchTableHeight()

    console.log(JSON.stringify(this.data))
    if (this.data) {
      this.tableData = this.data
    } else {
      this.tableData = []
    }
  },
  computed: {
    // 实时更新server
    // server: function () {
    //   return this.api.split('.')[0]
    // },
    // 实时更新url
    // url: function () {
    //   return this.api.split('.')[1]
    // },
  },
  methods: {
    fetch (query, method, url, callback, successback, errorback, pageChange) {
    //  this.loading = true
    //   {
    //     "filters": [
    //     {
    //       "operator": "string",
    //       "property": "string",
    //       "value": {}
    //     }
    //   ],
    //     "page": 0,
    //     "query": [
    //     {
    //       "property": "string",
    //       "value": {}
    //     }
    //   ],
    //     "sidx": "string",
    //     "size": 0,
    //     "sort": "string"
    //   }
      this.loading = true
      // 如果有分页, 执行此方法重置分页为1，如果是分页触发才不用改变
      if (pageChange !== 'change' && this.paging) {
        this.params.page = 1
      }

      if (url) {
        this.api = url
      }
      if (query) {
        this.query = query
      }
      if (method) {
        this.requestMethod = method
      }
      if (callback) {
        this.callback = callback
      }
      if (successback) {
        this.successback = successback
      }
      if (errorback) {
        this.errorback = errorback
      }

      var httpJson = {
        url: this.api,
        method: this.requestMethod
      }

      var httpParams = {
        page: this.params.page,
        size: this.params.limit,
        query: this.query
      }
      this.requestParams = httpParams
      if (this.requestMethod === 'get' || this.requestMethod === 'GET') {
        httpJson.params = httpParams
      } else if (this.requestMethod === 'post' || this.requestMethod === 'POST') {
        httpJson.data = httpParams
      }
      this.$http(httpJson).then(({ data }) => {
        console.log('fetch==' + data)
        this.loading = false
        if (this.successback) {
          this.successback(data)
        } else {
          this.tableData = data.rows || []
          // 如果有分页
          if (this.paging) {
            this.total = data.records || 0
            // this.params.page = data.curr || 0
          }
          if (this.callback) {
            this.callback(data)
          }
        }
      }).catch((data) => {
        this.loading = false
        if (this.errorback) {
          this.errorback(data)
        } else {
          this.$message({
            message: '系统异常',
            type: 'error'
          })
        }
      })
    },

    init (params) {
      this.loading = true
      // 如果采用微服务的方式需要传微服务和url
      this.$http({
        url: 'http://192.168.0.68:3003/api/cust/countCustByType/detail/2019?page=1&results=10&',
        method: this.method ? this.method : 'get',
        params: params
      }).then(({ data }) => {
        this.tableData = data.data || []
        // 如果有分页
        if (this.paging) {
          this.total = data.count || 0
          this.params.page = data.curr || 0
        }
        this.loading = false
      })
    },
    // 重新请求 //如果需要重新请求使用$refs 调用这个方法
    reload () {
      // 如果有分页
      if (this.paging) {
        this.params.page = 1
      }
      // api动态加载完 开始重新请求数据
      this.$nextTick(() => {
        // this.init(this.params)
        this.fetch()
      })
    },
    // 以下是对el-table原来的方法再次封装emit出去
    // 多选
    selectionChange (val) {
      this.selections = val
      this.$emit('selection-change', val)
    },
    // 单选
    currentChange (currentRow, oldCurrentRow) {
      this.$emit('current-change', currentRow, oldCurrentRow)
    },
    rowClick (row, event, column) {
      this.$emit('row-click', row, event, column)
    },
    // 排序
    sortChange (column, prop, order) {
      this.$emit('sort-change', column, prop, order)
    },
    // 表格翻页
    pageChange (page) {
      this.params.page = page
      // this.fetch(this.params)
      this.fetch(null, null, null, null, null, null, 'change')
    },
    limitChange (limit) {
      this.params.limit = limit
      // this.fetch(this.params)
      this.fetch()
    },
    getParamsObj () {
      var obj = {}
      this.requestParams.query.forEach(item => {
        obj[item.property] = item.value
      })
      return obj
    },

    watchTableHeight () {
      if (!this.cancelMinHeight) {
        if (this.tableHeight.replace('px', '') < 260) {
          this.height = '260px'
        } else {
          this.height = this.tableHeight
        }
      } else {
        //  不设置最小高度，为了某些静态表
        this.height = 'auto'
      }
    }
  }
}
</script>
